package com.ygl.consumer.lb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * @Author yanggld
 * @Date 2019/11/21-10:55
 * @Description
 * 自定义随机负载均衡器。实现负载均衡的服务间调用
 */
@Component
public class MyLoadBalance {

	@Autowired
	private DiscoveryClient discoveryClient;

	public String randomGetUri(String serviceId){
		// 获取目标微服务的所有实例的请求地址
		List<String> targetUris  = discoveryClient.getInstances(serviceId).stream()
				.map(t -> t.getUri().toString())
				.collect(Collectors.toList());
		// 随机获取列表中的uri
		int random = ThreadLocalRandom.current().nextInt(targetUris.size());
		String uri = targetUris.get(random);
		return uri;
	}
}
